package com.zlll.winner.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zlll.winner.business.model.bbs.BbsPost;
import com.zlll.winner.business.model.bbs.BbsPostMedia;
import com.zlll.winner.business.model.bbs.BbsUserActionLog;
import com.zlll.winner.business.model.bbs.BbsUserComment;
import com.zlll.winner.business.service.area.IAreaCityService;
import com.zlll.winner.business.service.bbs.*;
import com.zlll.winner.business.vo.bbs.BbsPostVo;
import com.zlll.winner.business.vo.bbs.BbsUserCommentVo;
import com.zlll.winner.common.BaseController;
import com.zlll.winner.common.BaseResult;
import com.zlll.winner.enums.CommonEnum;
import com.zlll.winner.enums.bbs.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("api/bbs/post")
@RestController
public class BbsPostController extends BaseController {

    @Reference(version = "${dubbo.consumer.version}")
    private IBbsSubjectService subjectService;

    @Reference(version = "${dubbo.consumer.version}")
    private IBbsPostService postService;

    @Reference(version = "${dubbo.consumer.version}")
    private IAreaCityService areaCityService;

    @Reference(version = "${dubbo.consumer.version}")
    private IBbsPostMediaService postMediaService;

    @Reference(version = "${dubbo.consumer.version}")
    private IBbsUserCommentService userCommentService;

    @Reference(version = "${dubbo.consumer.version}")
    private IBbsUserActionLogService userActionLogService;


    /**
     * 获取贴子详情
     * @param params
     * @return
     */
    @PostMapping("info")
    public Object info(@RequestBody JSONObject params){
        Long postId = params.getLong("postId");
        Assert.notNull(postId,"贴子ID不能为空");
        Long userId = params.getLong("userId");
        BbsPostVo result = postService.getDetailsById(postId,userId);
        return result == null? getEmptyResult(): result;
    }

    /**
     * 获取频道贴子分页列表
     * @param params
     * @return
     */
    @PostMapping("list")
    public Object postList(@RequestBody JSONObject params){
        Integer pageNo = params.getInteger("pageNo");
        Integer pageSize = params.getInteger("pageSize");
        Integer position = params.getInteger("position");

        String city = params.getString("city");

        Assert.notNull(pageNo,"pageNo不能为空");
        Assert.notNull(pageSize,"pageSize不能为空");
        Assert.notNull(position,"频道不能为空");

        if(position.equals(SubjectEnum.PositionEnum.CITY.val())){
            Assert.notNull(city,"城市不能为空");
        }
        Object result = postService.fetchPostPageByWeapp(params);
        return result == null? getEmptyResult(): result;
    }

    /***
     * 发布帖子
     * @param params
     * @return
     */
    @PostMapping("issue")
    public Object savePost(@RequestBody JSONObject params) throws InterruptedException {

        Integer count = postService.checkUserTodayIssueSum(params.getLong("userId"));
        Assert.isTrue(count<=20,"本日内最多发布20个语音视频帖子");

        BbsPost bbsPost = params.toJavaObject(BbsPost.class);
        Integer postType = params.getInteger("postType");
        if(1 == postType){
            Assert.notNull(bbsPost.getSubjectId(),"话题ID不能为空");
        }else{
            bbsPost.setSubjectId(null);
            Assert.notNull(bbsPost.getPosition(),"频道标识不能为空");
        }
        Assert.notNull(bbsPost.getUserId(),"用户ID不能为空");
        Assert.notNull(bbsPost.getUserImg(),"用户头像不能为空");
        Assert.notNull(bbsPost.getUserName(),"用户名不能为空");
        Assert.notNull(bbsPost.getType(),"贴子类型不能为空");

        if(bbsPost.getType().equals( PostEnum.TypeEnum.IMAGE.val())){
            JSONArray imageList = params.getJSONArray("imageList");
            Assert.notNull(imageList,"图片不能为空");
            Assert.isTrue(imageList.size() > 0,"图片不能为空");
        }else{
            String fileName = params.getString("fileName");
            if(bbsPost.getType().equals( PostEnum.TypeEnum.AUDIO.val())){
                Assert.isTrue(StringUtils.isNotBlank(fileName),"语音不能为空");
            }else if(bbsPost.getType().equals( PostEnum.TypeEnum.VIDEO.val())){
                Assert.isTrue(StringUtils.isNotBlank(fileName),"视频不能为空");
            }
        }
        bbsPost.setStatus(PostEnum.StatusEnum.PUT_AWAY.val());

        String city = params.getString("city");
        String cityCode = areaCityService.getCityCode(city);

        bbsPost.setCityCode(cityCode);
        bbsPost.setCityName(city);

        Object result = postService.save(bbsPost, params);
        return result == null? getEmptyResult(): result;
    }


    @PostMapping("comment/list")
    public Object commentList(@RequestBody JSONObject params){
        Integer pageNo = params.getInteger("pageNo");
        Integer pageSize = params.getInteger("pageSize");
        Long postId = params.getLong("postId");

        Assert.notNull(pageNo,"pageNo不能为空");
        Assert.notNull(pageSize,"pageSize不能为空");
        Assert.notNull(postId,"贴子ID不能为空");

        Object result = userCommentService.fetchCommentPage(params);
        return result == null? getEmptyResult(): result;
    }

    /**
     * 保存与更新
     * @param params
     * @return
     */
    @PostMapping(value = "comment/save")
    public Object save(@RequestBody JSONObject params) throws InterruptedException {
        BbsUserComment userComment = params.toJavaObject(BbsUserComment.class);
        Long postId = params.getLong("postId");

        Assert.notNull(userComment.getUserId(),"用户ID不能为空");
        Assert.notNull(userComment.getUserImg(),"用户头像不能为空");
        Assert.notNull(userComment.getUserName(),"用户名称不能为空");
        Assert.notNull(postId,"贴子ID不能为空");

        userComment.setBizId(postId);
        userComment.setBizType(CommentEnum.BizTypeEnum.POST.val());
        if(userComment.getId()!= null){
            userComment.setUpdateTime(System.currentTimeMillis());
        }else{
            userComment.setCreateTime(System.currentTimeMillis());
            userComment.setUpdateTime(userComment.getCreateTime());
        }
        userComment.setStatus(CommentEnum.StatusEnum.PUT_AWAY.val());
        Object result = userCommentService.saveOrUpdateComment(userComment);

        if(result!=null){
            if(userComment.getParentId()!=null){
                params.put("bizId", userComment.getParentId());
                params.put("bizType", ActionLogEnum.BizTypeEnum.COMMENT.val());
                params.put("actionType", ActionLogEnum.ActionTypeEnum.REPLY.val());
                params.put("actionBizType",ActionLogEnum.ActionBizTypeEnum.REPLY.val());
                params.put("actionBizId", ((BbsUserCommentVo)result).getId());
                userActionLogService.saveLog(params);
            }else {
                params.put("bizId", postId);
                params.put("bizType", ActionLogEnum.BizTypeEnum.POST.val());
                params.put("actionType", ActionLogEnum.ActionTypeEnum.COMMENT.val());
                params.put("actionBizType",ActionLogEnum.ActionBizTypeEnum.COMMENT.val());
                params.put("actionBizId",((BbsUserCommentVo)result).getId());
                userActionLogService.saveLog(params);
            }
        }
        return result;
    }

    @PostMapping(value = "comment/remove")
    public Object deleteComment(@RequestBody JSONObject params) throws InterruptedException {
        Long postId = params.getLong("postId");
        Long commentId = params.getLong("commentId");
        Long userId = params.getLong("userId");
        Assert.notNull(postId,"帖子标识不能为空");
        Assert.notNull(commentId,"评论标识不能为空");
        Assert.notNull(userId,"用户标识不能为空");
        BbsUserComment byId = userCommentService.getById(commentId);
        Assert.isTrue(byId.getUserId().equals(userId),"该评论不属于您的评论无法删除");
        Assert.isTrue(byId.getIsDel().equals(CommonEnum.DelEnum.UNDEL.val()),"该评论已经删除");
        Object o = userCommentService.removeComment(params);
        return byId;

    }
    /**
     * 用户操作帖子
     * @return
     */
    @PostMapping(value = "action")
    public Object action(@RequestBody JSONObject params) throws InterruptedException {
        Integer actionType = params.getInteger("actionType");
        Long bizId = params.getLong("bizId");
        Integer bizType = params.getInteger("bizType");
        Long userId = params.getLong("userId");
        if(actionType == ActionLogEnum.ActionTypeEnum.LIKE.val()){
            List<BbsUserActionLog> bbsUserActionLogs = userActionLogService.getBbsUserActionLogs(bizId, bizType, userId, actionType);
            if(bbsUserActionLogs!=null && bbsUserActionLogs.size() > 0){
                bbsUserActionLogs.forEach(item->{
                    item.setIsDel(CommonEnum.DelEnum.DEL.val());
                    item.setUpdateTime(System.currentTimeMillis());
                });
                userActionLogService.updateBatchById(bbsUserActionLogs);
                params.put("actionType",ActionLogEnum.ActionTypeEnum.UNLIKE.val());
            }
        }
        Object result = userActionLogService.saveLog(params);
        return result == null? getEmptyResult(): result;
    }

    /**
     * 获取视频截图
     * @param params
     * @return
     */
    @PostMapping(value = "getVideoImage")
    public Object getVideoImage(@RequestBody JSONObject params){
        String fileName = params.getString("fileName");
        BaseResult result = getEmptyResult();
        result.setBizContent(postService.getVideoImage(fileName));
        return result;
    }

    /**
     * 获取用户消息
     * @param params
     * @return
     */
    @PostMapping(value = "userMsg")
    public Object getUserMessagePage(@RequestBody JSONObject params){
        Integer pageNo = params.getInteger("pageNo");
        Integer pageSize = params.getInteger("pageSize");
        Long userId = params.getLong("userId");

        Assert.notNull(pageNo,"pageNo不能为空");
        Assert.notNull(pageSize,"pageSize不能为空");
        Assert.notNull(userId,"用户标识能为空");

        return userActionLogService.getLogByUserId(params);
    }
}
